package com.cgsrp.cgsrp_user_province.controller;

import com.cgsrp.cgsrp_user_province.domain.Carousel;
import com.cgsrp.cgsrp_user_province.domain.User;
import com.cgsrp.cgsrp_user_province.service.CarouselService;
import com.cgsrp.cgsrp_user_province.service.SendSMSService;
import com.cgsrp.cgsrp_user_province.service.UserService;
import com.cgsrp.utils.Result;
import com.cgsrp.vo.LoginVo;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.time.Duration;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private SendSMSService sendSMSService;
    @Autowired
    private CarouselService carouselService;

    /**
     * 获取验证码 使用captcha库实现的
     * @param httpServletResponse
     * @throws Exception
     */
    @GetMapping("/kaptcha")
    public Object defaultKaptcha(HttpServletResponse httpServletResponse) throws Exception{
        /*httpServletResponse.setHeader("Cache-Control","no-store");
        httpServletResponse.setHeader("Pragma","no-cache");
        httpServletResponse.setDateHeader("Expires",0);
        httpServletResponse.setContentType("image/gif");*/

        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //生成验证码对象,三个参数分别是宽、高、位数
        SpecCaptcha captcha = new SpecCaptcha(90, 30, 5);
        //设置验证码的字符类型为数字和字母混合
        captcha.setCharType(Captcha.TYPE_DEFAULT);
        // 设置内置字体
        captcha.setCharType(Captcha.FONT_3);
        // 生成一个随机的UUID
        UUID uuid = UUID.randomUUID();
        // 获取UUID的字符串表示
        String UUID = uuid.toString();
        //将验证码存入redis中，过期时间为5分钟
        Duration expiration = Duration.ofMinutes(5);
        ops.set(UUID,captcha.text().toLowerCase(),expiration);
        //验证码存入session
        //httpServletRequest.getSession().setAttribute("verifyCode",captcha.text().toLowerCase());
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        captcha.out(os);
        byte[] imageBytes = os.toByteArray();
        String base64Image = Base64.encodeBase64String(imageBytes);
        //输出图片流
//      captcha.out(httpServletResponse.getOutputStream());
        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        class CodeUse{
            private String base64Image;
            private String UUID;
        }
        CodeUse codeUse = new CodeUse();
        codeUse.setBase64Image(base64Image);
        codeUse.setUUID(UUID);
        System.out.println(UUID);
        return codeUse;
    }

    /**
     * login，实现的是登录功能
     * @param code 验证码
     * @param user 用户（其中传过来的只有 用户名以及密码，其中的用户名可以是该账号的用户名/手机号/邮箱）
     * @return
     */
    @RequestMapping("/verify")
    public LoginVo verify(@RequestParam("code") String code, User user,String uuid){
        System.out.println("code = " + code + ", user = " + user);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        LoginVo loginVo=new LoginVo();

        if (!StringUtils.hasLength(code)){
            loginVo.setResult(Result.failure("验证码不能为空"));
            return loginVo;
        }
        //String kaptchaCode = session.getAttribute("verifyCode")+"";
        String kaptchaCode = ops.get(uuid);
        System.out.println(kaptchaCode);
        if (kaptchaCode==null){
            loginVo.setResult(Result.failure("验证码已过期，请刷新验证"));
            return loginVo;
        }
        if (!StringUtils.hasLength(kaptchaCode)||!code.toLowerCase().equals(kaptchaCode)){
            loginVo.setResult(Result.failure("验证码错误"));
            return loginVo;
        }

        return userService.login(user);
    }

    @RequestMapping("checkphone")
    public boolean checkphone(String phone){
        return userService.selectByPhone(phone);
    }
    @RequestMapping("checkemail")
    public boolean checkemail(String email){
        return userService.selectByEmail(email);
    }

    @GetMapping("sendcode")
    public boolean sendcode(String phone){
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000;
        String code=String.valueOf(randomNumber);
        System.out.println(code);
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        Duration expiration = Duration.ofMinutes(5);
        ops.set(phone,code,expiration);
        return sendSMSService.sendSMS(phone,"SMS_464320848",code);
    }
    @GetMapping("checkcode")
    public Object checkcode(String code,String phone){
        @Data
        @AllArgsConstructor
        @NoArgsConstructor
        class Vo{
            private boolean flag;
            private String msg;
        }
        Vo vo = new Vo();
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String phoneCode=ops.get(phone);
        if (phoneCode==null){
            vo.setFlag(false);
            vo.setMsg("验证码已过期，请重新获取验证码");
            return vo;
        }
        if (phoneCode.equals(code)){
            vo.setMsg("验证通过");
            vo.setFlag(true);
            return vo;
        }else {
            vo.setFlag(false);
            vo.setMsg("验证码错误");
            return vo;
        }
    }

    @PostMapping("regist")
    public Object regist(User user){
        System.out.println("user = " + user);
        return userService.regist(user);
    }

    @PostMapping("update")
    public Result update(User user){
        int i = userService.updateByPrimaryKeySelective(user);
        if (i>0){
            return Result.success("修改成功");
        }else {
            return Result.failure("修改失败");
        }
    }

    @GetMapping("getWallet")
    public Result getWallet(Integer userId){
        return userService.getWallet(userId);
    }

    @GetMapping("carousel")
    public List<Carousel> carouselList(){
        return carouselService.list();
    }
}
